package com.zkt.weichat.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.zkt.weichat.handler.WeichatMsgFactory;
import com.zkt.weichat.handler.WeichatMsgHandler;
import com.zkt.weichat.utils.MessageUtil;
import com.zkt.weichat.utils.SHA1;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/22 23:57
 * @description 微信回调controller层
 **/

@RestController
@RequestMapping("/weichat")
@Slf4j
public class CallBackController {
	
	@Resource
	private WeichatMsgFactory weichatMsgFactory;
	
	private static final String TOKEN = "zkghauihg";
	
	/**
	 * 回调消息校验
	 *
	 * @param signature 微信加密签名
	 * @param timestamp 时间戳
	 * @param nonce     随机数
	 * @param echostr   随机字符串
	 * @return echostr
	 */
	@GetMapping("callBack")
	public String callBack(
			@RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce,
			@RequestParam("echostr") String echostr) {
		log.info("get验签请求参数：signature：{}，timestamp：{}，nonce：{}，echostr：{}", signature, timestamp, nonce, echostr);
		
		String shaStr = SHA1.sha1(TOKEN, timestamp, nonce);
		if (signature.equals(shaStr)) {
			return echostr;
		}
		return "unknown";
	}
	
	/**
	 * 回调消息校验
	 *
	 * @param signature    微信加密签名
	 * @param timestamp    时间戳
	 * @param nonce        随机数
	 * @param msgSignature 加密消息
	 * @return
	 */
	@PostMapping(value = "callBack", produces = "application/xml;charset=UTF-8")
	public String callBack(
			@RequestBody String body,
			@RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce,
			@RequestParam(value = "msg_signature", required = false) String msgSignature) {
		log.info("接收到微信的请求：body：{}，signature：{}，timestamp：{}，nonce：{}", body, signature, timestamp, nonce);
		
		Map<String, String> msgMap = MessageUtil.parseXml(body);
		String msgType = msgMap.get("MsgType");
		String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
		
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(msgType);
		if (StrUtil.isNotBlank(event)) {
			stringBuilder.append(".");
			stringBuilder.append(event);
		}
		
		String msgTypeKey = stringBuilder.toString();
		
		WeichatMsgHandler weichatMsgHandler = weichatMsgFactory.getHandlerByMsgType(msgTypeKey);
		if (ObjUtil.isEmpty(weichatMsgHandler)) {
			return "unknown";
		}
		
		String replyContent = weichatMsgHandler.dealMsg(msgMap);
		log.info("replyContent：{}", replyContent);
		return replyContent;
	}
	
}